package com.amado.easyui2.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

import com.amado.easyui2.service.ExportService;
import com.amado.easyui2.service.impl.ExportServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;


public class ExportServlet<T> extends HttpServlet {
	private ExportService exportService = new ExportServiceImpl();
	private static ObjectMapper mapper = new ObjectMapper();
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("UTF-8");
		arg1.setCharacterEncoding("UTF-8");
		PrintWriter out = arg1.getWriter();
		out.print(mapper.writeValueAsString(exportService.listAll()));
	}
	
	 public HSSFWorkbook exportExcel(String title, String[] headers, List<T> dataset) {

	        // 声明一个工作薄  
	        HSSFWorkbook workbook = new HSSFWorkbook();
	        // 生成一个表格  
	        HSSFSheet sheet = workbook.createSheet(title);
	        // 设置表格默认列宽度为15个字节  
	        sheet.setDefaultColumnWidth((short) 15);  
	        
	        // 生成一个样式  
	        HSSFCellStyle style = workbook.createCellStyle();
	        // 设置这些样式  
	        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
	        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
	        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
	        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
	        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
	        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
	        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	        
	        // 生成一个字体  
	        HSSFFont font = workbook.createFont();
	        font.setColor(HSSFColor.VIOLET.index);
	        font.setFontHeightInPoints((short) 12);
	        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

	        // 把字体应用到当前的样式  
	        style.setFont(font);
	        // 生成并设置另一个样式  
	        HSSFCellStyle style2 = workbook.createCellStyle();
	        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
	        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
	        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
	        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
	        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
	        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
	        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	        // 生成另一个字体  
	        HSSFFont font2 = workbook.createFont();
	        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
	        // 把字体应用到当前的样式  
	        style2.setFont(font2);

	        // 产生表格标题行  
	        HSSFRow row = sheet.createRow(0);
	        for (short i = 0; i < headers.length; i++) {
	            HSSFCell cell = row.createCell(i);
	            cell.setCellStyle(style);
	            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
	            cell.setCellValue(text);
	        }

	        // 遍历集合数据，产生数据行  
	        Iterator<T> it = dataset.iterator();
	        int index = 0;

	        try {

	            while (it.hasNext()) {
	                index++;
	                row = sheet.createRow(index);
	                T t = (T) it.next();

	                // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值  
	                Field[] fields = t.getClass().getDeclaredFields();
	                for (short i = 0; i < fields.length; i++) {
	                    HSSFCell cell = row.createCell(i);
	                    cell.setCellStyle(style2);
	                    Field field = fields[i];
	                    String fieldName = field.getName();
	                    String getMethodName = "get"
	                            + fieldName.substring(0, 1).toUpperCase()
	                            + fieldName.substring(1);

	                    Class tCls = t.getClass();

	                    Method getMethod = tCls.getMethod(getMethodName, new Class[]{});

	                    Object value = getMethod.invoke(t, new Object[]{});

	                    //全部当做字符串来处理
	                    String textValue = value.toString();
	           
	                    if (textValue != null) {
	                        HSSFRichTextString richString = new HSSFRichTextString(textValue);
	                        HSSFFont font3 = workbook.createFont();
	                        font3.setColor(HSSFColor.BLUE.index);
	                        richString.applyFont(font3);
	                        cell.setCellValue(richString);
	                    }
	                }
	            }

	        } catch (NoSuchMethodException ex) {
	            Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex);
	        } catch (SecurityException ex) {
	            Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex);
	        } catch (IllegalAccessException ex) {
	            Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex);
	        } catch (IllegalArgumentException ex) {
	            Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex);
	        } catch (InvocationTargetException ex) {
	            Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex);
	        }
	        
	        return workbook;
	    }
}
